package org.example;

import lombok.Getter;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
//封装响应数据
public class MyHttpResponse {
    private static final int BUFFER_SIZE = 1024;
    //响应对应的请求
    private MyHttpRequest request;
    private OutputStream socketOutputStream;
    private byte SP=' ';
    private byte CR='\r';
    private byte LF='\n';
    //响应行
    private int code=200;
    private String message="ok";
    //响应头
    private Map<String,String> HeaderMap=new HashMap<>();
    //响应体
    @Getter
    private MyPrintWriter printWriter=new MyPrintWriter();

    public MyHttpResponse(MyHttpRequest request, Socket socket) throws IOException {
        this.request = request;
        socketOutputStream=request.getSocket().getOutputStream();
    }
    public void addHeader(String s, String s1) {

        HeaderMap.put(s,s1);
    }
    //定义一个响应体写入结束的方法
    public void complete() throws IOException {
        System.out.println("complete 方法");
        sendResponseLine();
        sendResponseHeader();
        sendResponseBody();
    }
    //响应响应行
    private void sendResponseLine() throws IOException {
        socketOutputStream.write("HTTP/1.1".getBytes());
        socketOutputStream.write(SP);
        socketOutputStream.write(code);
        socketOutputStream.write(SP);
        socketOutputStream.write(message.getBytes());
        socketOutputStream.write(CR);
        socketOutputStream.write(LF);
    }

    //响应响应头
    private void sendResponseHeader() throws IOException {
        //自动加上相应的响应头
        if(!HeaderMap.containsKey("Content-Length")){
            addHeader("Content-Length",String.valueOf(getPrintWriter().getPos()));
        }
        //遍历响应头集合
        Set<Map.Entry<String, String>> entries = HeaderMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String key=entry.getKey();
            String value=entry.getValue();
            socketOutputStream.write(key.getBytes());
            socketOutputStream.write(":".getBytes());
            socketOutputStream.write(value.getBytes());
            socketOutputStream.write(CR);
            socketOutputStream.write(LF);
        }
        socketOutputStream.write(CR);
        socketOutputStream.write(LF);
    }
    //响应响应体
    private void sendResponseBody() throws IOException {
        socketOutputStream.write(getPrintWriter().getBytes());
    }
}
